<template>
  <div>
    <van-cell-group>
      <van-field
        v-model="userForm.username"
        required
        clearable
        label="用户名"
        right-icon="question-o"
        placeholder="请输入用户名"
        @click-right-icon="$toast('输入用户名')"
      />
      <van-field
        v-model="userForm.password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
      />
    </van-cell-group>
    <div class="mt20">
      <van-button size="large" type="primary" @click="userLoginHandle">登录</van-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SignIn',
  data() {
    return {
      redirect: undefined,
      userForm: {
        username: '',
        password: ''
      },
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  methods: {
    userLoginHandle() {
      this.$store.dispatch('user/login', this.userForm).then(res => {
        this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style scoped>

</style>
